package com.javachmapi.springbootmysqlmybatisredis.service;

import com.javachmapi.springbootmysqlmybatisredis.dao.CustomerMapper;
import com.javachmapi.springbootmysqlmybatisredis.entity.Customer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class CustomerService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private RedisTemplate<String, Customer> redisTemplate;

    /**
     * 创建客户
     * 不会对缓存做任何操作
     */
    public int createCustomer(Customer customer) {
        logger.info("创建客户start...");
        return customerMapper.save(customer);
    }

    /**
     * 获取客户信息
     * 如果缓存存在，从缓存中获取城市信息
     * 如果缓存不存在，从 DB 中获取城市信息，然后插入缓存
     *
     * @param id 客户ID
     * @return 客户
     */
    public Customer getById(Integer id) {
        logger.info("获取客户start...");
        // 从缓存中获取客户信息
        String key = "cunstomer_" + id;
        ValueOperations<String, Customer> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            Customer customer = operations.get(key);
            logger.info("从缓存中获取了客户 id = " + id);
            return customer;
        }
        // 缓存不存在，从 DB 中获取
        Customer customer = customerMapper.getById(id);
        // 插入缓存
        operations.set(key, customer, 10, TimeUnit.SECONDS);
        return customer;
    }

    /**
     * 更新客户
     * 如果缓存存在，删除
     * 如果缓存不存在，不操作
     *
     * @param customer 客户
     */
    public void updateCustomer(Customer customer) {
        logger.info("更新客户start...");
        customerMapper.update(customer);
        int customerId = customer.getId();
        // 缓存存在，删除缓存
        String key = "customer_" + customerId;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);
            logger.info("更新客户时候，从缓存中删除客户 >> " + customerId);
        }
    }

    /**
     * 删除客户
     * 如果缓存中存在，删除
     */
    public void deleteById(Integer id) {
        logger.info("删除客户start...");
        customerMapper.delete(id);

        // 缓存存在，删除缓存
        String key = "customer_" + id;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);
            logger.info("删除客户时候，从缓存中删除客户 >> " + id);
        }
    }
}
